<template>
    <view class="edit-container">
        <view class="form-group">
            <view class="form-item">
                <text class="label">姓名</text>
                <input type="text" v-model="addressForm.name" placeholder="收货人姓名" @blur="handleNameBlur"
                    maxlength="20" />
            </view>
            <view class="form-item">
                <text class="label">电话</text>
                <input type="number" v-model="addressForm.tel" placeholder="手机号码" maxlength="11"
                    @blur="handlePhoneBlur" />
            </view>
            <view class="form-item">
                <text class="label">地区</text>
                <picker mode="region" :value="region" @change="handleRegionChange">
                    <view class="region-select">
                        <text v-if="addressForm.province" class="region-text">
                            {{ addressForm.province + addressForm.city + addressForm.county }}
                        </text>
                        <text v-else class="placeholder">选择地区</text>
                        <text class="arrow">></text>
                    </view>
                </picker>
            </view>
            <view class="form-item">
                <text class="label">详细地址</text>
                <input type="text" v-model="addressForm.address" placeholder="如街道、楼牌号等" @blur="handleAddressBlur" />
            </view>
            <view class="form-item">
                <text class="label">邮政编码</text>
                <input type="number" v-model="addressForm.postalCode" placeholder="邮政编码" maxlength="6" />
            </view>
        </view>

        <view class="default-item">
            <text>设为默认收货地址</text>
            <switch :checked="addressForm.isDefault" @change="handleDefaultChange" color="#576B95" />
        </view>

        <view class="btn-group">
            <view class="save-btn" @tap="handleSave">保存</view>
        </view>
    </view>
</template>

<style lang="scss" scoped>
.edit-container {
    min-height: 100vh;
    background-color: #f7f7f7;
    padding-bottom: 40rpx;

    .form-group {
        background-color: #ffffff;
        margin-top: 20rpx;

        .form-item {
            display: flex;
            align-items: center;
            min-height: 100rpx;
            padding: 0 32rpx;
            border-bottom: 1rpx solid #eee;

            &:last-child {
                border-bottom: none;
            }

            .label {
                width: 140rpx;
                font-size: 28rpx;
                color: #000;
            }

            input {
                flex: 1;
                font-size: 28rpx;
                color: #000;

                &::placeholder {
                    color: #888;
                    font-size: 28rpx;
                }
            }

            .region-select {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .region-text,
                .placeholder {
                    font-size: 28rpx;
                    color: #000;
                }

                .placeholder {
                    color: #888;
                }

                .arrow {
                    color: #888;
                    font-size: 28rpx;
                }
            }
        }
    }

    .default-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background-color: #fff;
        margin-top: 20rpx;
        padding: 0 32rpx;
        height: 100rpx;
        font-size: 28rpx;
        color: #000;
    }

    .btn-group {
        padding: 40rpx 32rpx;

        .save-btn {
            height: 88rpx;
            line-height: 88rpx;
            text-align: center;
            font-size: 32rpx;
            border-radius: 4rpx;
            background-color: #ff4444;
            color: #fff;
        }
    }
}
</style>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { reqAddUserAddress, reqUpdUserAddress } from '@/api/user';
import { useUserStore } from '@/store';
const userStore = useUserStore();

// 地址ID
const addressId = ref('');

// 地区选择器的值
const region = ref(['', '', '']);

// 地址表单
const addressForm = ref({
    name: '',           // 收货人姓名
    tel: '',           // 手机号码
    province: '',      // 省份
    city: '',          // 城市
    address: '',       // 详细地址
    addressDetail: '', // 详细地址（与address保持一致）
    areaCode: '',      // 区域编码
    county: '',       // 县区
    isDefault: false,  // 是否默认地址
    postalCode: ''     // 邮政编码
});

// 处理地区选择变化
const handleRegionChange = (e) => {
    const detail = e.detail;
    region.value = detail.value;
    console.log('地区选择完整信息:', detail);

    // 更新表单数据
    addressForm.value.province = detail.value[0];
    addressForm.value.city = detail.value[1];
    addressForm.value.county = detail.value[2];

    // 设置区域编码 - 增加错误处理和日志
    if (detail.code && Array.isArray(detail.code)) {
        addressForm.value.areaCode = detail.code[2] || detail.code[1] || detail.code[0] || '';
        console.log('区域编码设置为:', addressForm.value.areaCode);
    } else {
        console.log('警告: 未能获取区域编码，detail.code:', detail.code);
        // 如果没有code，尝试使用其他方式获取
        addressForm.value.areaCode = '';
    }

    console.log('设置的地址信息:', {
        province: addressForm.value.province,
        city: addressForm.value.city,
        county: addressForm.value.county,
        areaCode: addressForm.value.areaCode
    });
};

//回显数据，通过传过来的id获取数据
const findAddress = (id) => {
    console.log('查找地址ID:', id);
    console.log('地址列表:', userStore.addressList);
    const address = userStore.addressList.find(item => item.id === Number(id));
    console.log('找到的地址:', address);
    if (address) {
        // 更新表单数据
        addressForm.value = {
            name: address.name || '',
            tel: address.tel || '',
            province: address.province || '',
            city: address.city || '',
            address: address.address || '',
            addressDetail: address.address || '',
            areaCode: address.areaCode || '',
            county: address.county || '',  // 县区
            isDefault: !!address.isDefault,
            postalCode: address.postalCode || ''
        };

        // 更新地区选择器的值
        region.value = [
            addressForm.value.province || '',
            addressForm.value.city || '',
            addressForm.value.county || ''  // 使用county作为县区
        ];
        console.log('回显地区值:', region.value);
    }
};

// 表单验证规则
const validateForm = () => {
    // 验证姓名
    if (!addressForm.value.name) {
        uni.showToast({
            title: '请输入收货人姓名',
            icon: 'none'
        });
        return false;
    }
    if (addressForm.value.name.length < 2) {
        uni.showToast({
            title: '收货人姓名至少2个字符',
            icon: 'none'
        });
        return false;
    }
    if (addressForm.value.name.length > 20) {
        uni.showToast({
            title: '收货人姓名不能超过20个字符',
            icon: 'none'
        });
        return false;
    }

    // 验证手机号
    if (!addressForm.value.tel) {
        uni.showToast({
            title: '请输入手机号码',
            icon: 'none'
        });
        return false;
    }
    if (!/^1[3-9]\d{9}$/.test(addressForm.value.tel)) {
        uni.showToast({
            title: '请输入正确的手机号码',
            icon: 'none'
        });
        return false;
    }

    // 验证地区
    if (!addressForm.value.province || !addressForm.value.city || !addressForm.value.county) {
        uni.showToast({
            title: '请选择所在地区',
            icon: 'none'
        });
        return false;
    }

    // 验证详细地址
    if (!addressForm.value.address) {
        uni.showToast({
            title: '请输入详细地址',
            icon: 'none'
        });
        return false;
    }
    if (addressForm.value.address.length < 5) {
        uni.showToast({
            title: '详细地址至少5个字符',
            icon: 'none'
        });
        return false;
    }
    if (addressForm.value.address.length > 100) {
        uni.showToast({
            title: '详细地址不能超过100个字符',
            icon: 'none'
        });
        return false;
    }

    return true;
};

// 处理输入框失去焦点时的验证
const handleNameBlur = () => {
    if (addressForm.value.name && (addressForm.value.name.length < 2 || addressForm.value.name.length > 20)) {
        uni.showToast({
            title: '姓名长度应在2-20个字符之间',
            icon: 'none'
        });
    }
};

const handlePhoneBlur = () => {
    if (addressForm.value.tel && !/^1[3-9]\d{9}$/.test(addressForm.value.tel)) {
        uni.showToast({
            title: '请输入正确的手机号码',
            icon: 'none'
        });
    }
};

const handleAddressBlur = () => {
    if (addressForm.value.address && (addressForm.value.address.length < 5 || addressForm.value.address.length > 100)) {
        uni.showToast({
            title: '地址长度应在5-100个字符之间',
            icon: 'none'
        });
    }
};

// 处理默认地址切换
const handleDefaultChange = (e) => {
    addressForm.value.isDefault = e.detail.value;
};

// 处理保存
const handleSave = async () => {
    // 表单验证
    if (!validateForm()) return;

    // 准备提交的数据
    const submitData = {
        name: addressForm.value.name,
        tel: addressForm.value.tel,
        province: addressForm.value.province,
        city: addressForm.value.city,
        address: addressForm.value.address,
        addressDetail: addressForm.value.address,
        areaCode: addressForm.value.areaCode,
        county: addressForm.value.county,
        isDefault: addressForm.value.isDefault,
        postalCode: addressForm.value.postalCode
    };

    if (addressId.value) {
        // 编辑模式
        submitData.id = addressId.value;
        // 编辑模式
        console.log('编辑submitData', submitData);
        try {
            const res = await reqUpdUserAddress(submitData);
            console.log('更新地址响应:', res);
            if (res) {
                uni.showToast({
                    title: '更新成功',
                    icon: 'success'
                });
                //返回上一页
                uni.navigateBack();
            }
        } catch (error) {
            console.error('更新地址失败:', error);
            uni.showToast({
                title: '更新失败',
                icon: 'none'
            });
        }
    } else {
        // 新增模式
        console.log('新增submitData', submitData);
        try {
            const res = await reqAddUserAddress(submitData);
            console.log('新增地址响应:', res);
            if (res) {
                uni.showToast({
                    title: '添加成功',
                    icon: 'success'
                });
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
            }
        } catch (error) {
            console.error('新增地址失败:', error);
            uni.showToast({
                title: '添加失败',
                icon: 'none'
            });
        }
    }
};
// 页面加载
onLoad((options) => {
    if (options.id) {
        addressId.value = options.id;
        console.log('地址ID:', addressId.value);
        // 调用回显函数
        const address = userStore.addressList.find(item => item.id === Number(options.id));
        if (address) {
            console.log('回显地址数据:', address);
            // 更新表单数据
            addressForm.value.name = address.name;
            addressForm.value.tel = address.tel;
            addressForm.value.province = address.province;
            addressForm.value.city = address.city;
            addressForm.value.address = address.address;
            addressForm.value.addressDetail = address.address;
            addressForm.value.areaCode = address.areaCode;
            addressForm.value.county = address.county;
            addressForm.value.isDefault = address.isDefault;
            addressForm.value.postalCode = address.postalCode;

            // 更新地区选择器的值
            region.value = [address.province, address.city, address.country];
        }
    }
});
</script>